package com.tools.ad.adscene;

import com.hm.ads.sdk.HmAdsSDK;
import com.hm.adsbuisiness.bean.HmAdPlace;
import com.hm.adsbuisiness.bean.HmAdUnionPlace;
import com.tools.ad.util.RandomUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * desc:
 * date: 2018/1/4
 * author: ancun
 */

public class AdSceneUtil {

    public static HmAdUnionPlace getPlaceByArray(int[] pidArray) {
        //所有ad机率总和
        int total;
        //每个ad自身的机率域
        int[] scores;

        List<HmAdUnionPlace> placeIdList = new ArrayList<>();
        for (int i = 0; i < pidArray.length; i++) {
            HmAdUnionPlace unionAd = HmAdsSDK.getInstance().getUnionAd(pidArray[i]);
            if (unionAd != null) {
                placeIdList.add(unionAd);
            }
        }

        if (placeIdList.isEmpty()) {
            return null;
        }

        if (placeIdList.size() == 1) {
            return placeIdList.get(0);
        }

        int size = placeIdList.size();
        scores = new int[size];
        total = 0;
        for (int i = 0; i < size; i++) {
            HmAdPlace hmAdPlace = placeIdList.get(i);
            total += hmAdPlace.getChance();
            scores[i] = total;
        }
        return placeIdList.get(getRandomPlaceIndex(total, scores));
    }

    private static int getRandomPlaceIndex(int total, int[] scores) {
        int random = RandomUtil.getRandom().nextInt(99999) % total;
        int length = scores.length;
        for (int i = 0; i < length; i++) {
            if (scores[i] > random) {
                return i;
            }
        }
        return 0;
    }
}
